package com.cslc.mp.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cslc.mp.constant.MpInfo;
import com.cslc.mp.dao.DAOFactory;
import com.cslc.mp.dao.vo.User;
import com.cslc.mp.util.SignUtil;

public class BindServlet extends HttpServlet {
	private static Logger logger = Logger.getLogger(CoreServlet.class.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 微信加密签名 
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 微信用户id
        String openId = request.getParameter("OpenId");
        // 终端编码
        String terminalNo = request.getParameter("terminalNo");
        PrintWriter out = response.getWriter();  
        if(signature == null || signature.length() <= 0)
        	logger.error("signature为空！");
        else {
        	logger.debug("开始校验用户signature :" + signature);
          	//如果校验成功
        	if(signature.equals(SignUtil.createSignature(openId, MpInfo.TOKEN, timestamp))) {
            	logger.debug("signature校验成功");
            	//如果链接未超时
            	if(System.currentTimeMillis() - Long.parseLong(timestamp) < 60000) {
            		logger.debug("timestamp校验成功,未超时");
            		HttpSession session = request.getSession();
            		session.setAttribute("openid", openId);
            		session.setAttribute("terminalNo", terminalNo);
            		logger.debug("该用户的session id是：" + session.getId());
            		try {
                	   	response.sendRedirect(MpInfo.HOST + "/scan_bind.jsp");
    				} catch (Exception e) {
    					logger.error(e.getMessage());
    					response.getWriter().print(e);
    				}
            	}
            	else {
            		response.sendRedirect(MpInfo.HOST + "/bind_timeout.jsp");
            		logger.info("该链接已超时");
            	}
         
            }
            else {
            	logger.error("signature校验失败");
            }
        }    
        out.close();
        out = null;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		User user = setUser(request);
		
		//如果session中不空，即存在用户的openid
		if(user.getOpenid() != null) {
				
				boolean salerExist = DAOFactory.getIUserDAOInstance().queryUser(user);
				boolean openidExist = DAOFactory.getIUserDAOInstance().findById(user.getOpenid()) != null;
				//编号和密码都正确，且该用户之前未绑定过
				if(salerExist && !openidExist) {
					logger.debug("该销售员存在且该微信号未绑定过其他账号！");
					//将微信号与销售员账号绑定
					logger.debug("user.openid:" + user.getOpenid());
					if(DAOFactory.getIUserDAOInstance().bindUser(user)) {
						//用户绑定成功
						logger.info("用户绑定成功：" + user.getTerminalNo() + "-" + user.getSalerNo() + " : " + user.getOpenid());
				    	response.sendRedirect(MpInfo.HOST + "/bind_success.jsp");
					}
					else {
						logger.error("绑定失败！");
					}
				}
				else if(salerExist && openidExist == true){
						logger.info(user.getOpenid() + "已经被绑定");
				}
				else {
					logger.info("用户名或密码错误（终端编码，销售员号码，密码三者其一不存在）");
					response.sendRedirect(MpInfo.HOST + "/bind_failure.jsp");
				}
		}
		//如果session中不存在该用户openId，用户请求不合法
		else {
			logger.info("用户请求不合法！（session中不存在微信账户openid，不是当前用户请求，或者请求超时）");
			response.sendRedirect(MpInfo.HOST + "/bind_error.jsp");
		}
		
	}
	
	/**
	 * 从request中获取参数，构造user对象
	 * @param request
	 * @return
	 */
	private User setUser(HttpServletRequest request) {
		String terminalNo = request.getParameter("terminalNo");
		String salerNo = request.getParameter("salerNo");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("openid");
		logger.debug("sessionID: " + session.getId() + "终端编码：" + terminalNo + "  销售员号码：" + salerNo + " 密码：" + password);
		User user = new User();
		user.setTerminalNo(terminalNo);
		user.setSalerNo(salerNo);
		user.setPassword(password);
		user.setOpenid(openId);
		return user;
	}
}
